package server

import (
	"fmt"
	"shop-api/consts"
	"shop-api/databases/redis"
	"shop-api/internal/model"
	"shop-api/pkg/jwt"
	"shop-api/pkg/pwd"
)

type LoginReq struct {
	Phone string `json:"phone"`
	Code  string `json:"code"`
	Pwd   string `json:"pwd"`
	Type  int64  `json:"type"` //type=1 就是验证码登录  type=2 就是密码登录
}

type LoginResp struct {
	UserInfo *model.User `json:"user_info"`
	Token    string      `json:"token"`
}

func UpdateUser(in *model.User) (*model.User, error) {
	in.IgnorePassword = true
	return in.Update(in.ID)
}

func Register(in *LoginReq) (*LoginResp, error) {
	err := checkCode(in.Phone, in.Code)
	if err != nil {
		return nil, err
	}

	pwdStr, err := pwd.GetPwd(in.Pwd)
	if err != nil {
		return nil, err
	}

	mod := model.User{
		Phone:    in.Phone,
		Password: pwdStr,
	}

	userInfo, err := mod.GetByPhone(in.Phone)
	if err != nil {
		return nil, err
	}

	if userInfo != nil {
		return nil, fmt.Errorf("该手机号已注册")
	}

	mod.IgnorePassword = true
	userInfo, err = mod.Create()
	if err != nil {
		return nil, err
	}

	token, err := jwt.GenToken(userInfo.ID)
	if err != nil {
		return nil, err
	}

	return &LoginResp{
		UserInfo: userInfo,
		Token:    token,
	}, nil
}
func ForgetPwd(in *LoginReq) (*LoginResp, error) {
	err := checkCode(in.Phone, in.Code)
	if err != nil {
		return nil, err
	}

	pwdStr, err := pwd.GetPwd(in.Pwd)
	if err != nil {
		return nil, err
	}

	mod := model.User{
		Password: pwdStr,
	}

	userInfo, err := mod.GetByPhone(in.Phone)
	if err != nil {
		return nil, err
	}

	if userInfo == nil {
		return nil, fmt.Errorf("该手机号未注册")
	}

	userInfo, err = mod.Update(userInfo.ID)
	if err != nil {
		return nil, err
	}

	return &LoginResp{
		UserInfo: userInfo,
	}, nil
}

func Login(in *LoginReq) (*LoginResp, error) {
	if in.Type == consts.LoginTypeCode {
		err := checkCode(in.Phone, in.Code)
		if err != nil {
			return nil, err
		}
	}

	mod := new(model.User)
	mod.IgnorePassword = true
	userInfo, err := mod.GetByPhone(in.Phone)
	if err != nil {
		return nil, err
	}

	if userInfo == nil {
		return nil, fmt.Errorf("该手机号未注册")
	}

	if in.Type == consts.LoginTypePwd {
		ok := pwd.ComparePwd(userInfo.Password, in.Pwd)
		if !ok {
			return nil, fmt.Errorf("密码错误")
		}
	}

	userInfo.Password = ""
	token, err := jwt.GenToken(userInfo.ID)
	if err != nil {
		return nil, err
	}

	return &LoginResp{
		UserInfo: userInfo,
		Token:    token,
	}, nil
}

func checkCode(phone, code string) error {
	exist, err := redis.Exist(consts.SMSSendCode + phone)
	if err != nil {
		return err
	}

	if !exist {
		return fmt.Errorf("验证码不存在")
	}

	codeVal, err := redis.Get(consts.SMSSendCode + phone)
	if err != nil {
		return err
	}
	if codeVal != code {
		return fmt.Errorf("验证码错误")
	}
	return nil
}
